package org.ranki.moerae.atropos;

import org.ranki.moerae.clotho.node.AbstractNode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EliminateDeadlock implements Eliminate{
    private volatile static EliminateDeadlock eliminateDeadlock;
    private EliminateDeadlock (){}
    public static EliminateDeadlock getEliminateDeadlock() {
        if (eliminateDeadlock == null) {
            synchronized (EliminateDeadlock.class) {
                if (eliminateDeadlock == null) {
                    eliminateDeadlock = new EliminateDeadlock();
                }
            }
        }
        return eliminateDeadlock;
    }

    @Override
    public void eliminate(AbstractNode abstractNode) {
        dfs(abstractNode,new HashSet<>());
    }
    private void dfs(AbstractNode curr, Set<AbstractNode> seen){
        seen.add(curr);
        List<AbstractNode> nexts=new ArrayList<>();
        for(AbstractNode next: curr.getNexts()){
            nexts.add(next);
        }
        for(AbstractNode next:nexts){
            dfs(next,seen);
            if(next.getNexts().size()==0){
                curr.getNexts().remove(next);
            }
        }
    }
}
